#include <stdio.h>
#include <stdlib.h>

typedef struct Node{
  unsigned int data;
  struct Node* next;
} Node;

// 尾节点循环链表
Node* createJosephList(unsigned int n)
{
  if (n == 0) {
    return NULL;
  }
  Node* head = (Node*)malloc(sizeof(Node));
  if (head == NULL) {
    return NULL;
  }
  head->data = 1;

  Node* tail = head;
  for (unsigned int i = 1; i < n; ++i) {
    Node* p = (Node*)malloc(sizeof(Node));
    if (p == NULL) {
      // 释放内存
      return NULL;
    }
    p->data = i + 1;

    tail->next = p;
    tail = p;
  }
  tail->next = head;

  return tail;
}

unsigned int dealJosephList(Node* list, unsigned int n, unsigned int m)
{
  if ((list == NULL) || (m == 0)) {
    return 0;
  }
  if (m > n) {
    m = m % n;
  }

  Node* p = list;
  while (p->next != p) {
    for (unsigned int i = 1; i < m; ++i) {
      p = p->next;
    }

    Node* dp = p->next;
    // printf("%d->", dp->data);
    p->next = dp->next;
    free(dp);
  }
  // printf("%d\n", p->data);
  return p->data;
}

int josephList(unsigned int n, unsigned int m)
{
  if (n == 0 || m == 0) {
    return -1;
  }
  Node* list = createJosephList(n);
  if (list == NULL) {
    return -1;
  }

  return dealJosephList(list, n, m);
}

int josephRecur(unsigned int n, unsigned int m, unsigned int lucky)
{
  if (n == 0 || m == 0 || lucky == 0) {
    return -1;
  }
  if (lucky > n) {
    return -1;
  }
  unsigned int ret = lucky - 1;
  for (unsigned int i = 2; i <= n; ++i) {
    ret = (ret + m) % i;
  }
  return ret + 1;
}

int main(int argc, char* argv[])
{
  if (argc != 3) {
    return -1;
  }

  unsigned int n = atoi(argv[1]);
  unsigned int m = atoi(argv[2]);
  printf("%d\n", josephList(n, m));
  printf("%d\n", josephRecur(n, m, 1));
  printf("%d\n", josephRecur(n, m, 2));

  return 0;
}

